package com.photoeditor.demo.ui.widget.image.magazine;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.photoeditor.demo.db.MagazineBean;
import com.photoeditor.demo.model.image.collage.templet.MagazineRectf;
import com.photoeditor.demo.model.image.collage.util.CollageGestureRecognizer;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.ui.activity.edit.EditorImageActivity;
import com.photoeditor.demo.ui.widget.collage.BorderView;
import com.photoeditor.demo.ui.widget.collage.ICollage;
import com.photoeditor.demo.util.ImageRectUtils;

import java.util.ArrayList;

/**
 * @dest 拼接总试图
 */

public class EditMagazineCollageRelativeLayout extends RelativeLayout implements View.OnTouchListener, CollageGestureRecognizer.Listener {
    //View 的Rect  相对于整个屏幕的位置
    private RectF mViewRect;

    //子View的显示区域  相对于这个View的位置
    private RectF mAllChildRect;
    //是否初始化
    private boolean mIsInit = false;
    private float mRatio = 1;
    private MagazineRectf mTempletRectf;
    //保存拼接的所有图片
    private Bitmap mSourceBitmap;
    private Bitmap mBgBitmap;
    private Paint mBgPaint;
    private ICollage mCollage;
    private boolean mFlag = false;
    private final int SELECTED_NONE = 0;
    private final int SELECTED_AND_MOVE = 1;
    private final int SELECTED_AND_SCALE = 2;
    private int mTouchMode = SELECTED_NONE;
    private EditMagazineChildRectfView mCurrentOperationView;
    private CollageGestureRecognizer mGestureRecognizer;

    private int mItemPosition;
    private boolean mIsHasCoverView;
    private Bitmap mCoverBitmap;
    private EditorImageActivity mContext;
    private ArrayList<MagazineRectf> mMagazineRectfs;
    private ArrayList<MagazineBean> mMagazineDatas;

    public EditMagazineCollageRelativeLayout(Context context) {
        this(context, null);
    }

    public EditMagazineCollageRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EditMagazineCollageRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = (EditorImageActivity) context;
        initWidthAttr();
    }

    private void initWidthAttr() {
        setWillNotDraw(false);
        mCollage = (ICollage) getContext();
        mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBgPaint.setStyle(Paint.Style.FILL);
        mAllChildRect = new RectF();
        mViewRect = new RectF();

        setOnTouchListener(this);
        //添加手势
        mGestureRecognizer = new CollageGestureRecognizer(getContext(), this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            init(ImageRectUtils.getViewRect(this));
        }
    }

    private void init(RectF viewRect) {
        if (!mIsInit || !mViewRect.equals(viewRect)) {
            mIsInit = true;
            mViewRect = viewRect;

        }
    }

    /**
     * ------初始化------
     **/
    private void invalidateCollage() {
        removeAllViews();
        //计算当前模板要显示的内容大小
        if (mViewRect.width() / mRatio <= mViewRect.height()) {//变换后高变小了,需要重新调整高度(变小)
            mAllChildRect.left = 0;
            mAllChildRect.top = (mViewRect.height() - mViewRect.width() / mRatio) / 2;
            mAllChildRect.right = mViewRect.width();
            mAllChildRect.bottom = mAllChildRect.top + mViewRect.width() / mRatio;
        } else {
            mAllChildRect.left = (mViewRect.width() - mViewRect.height() * mRatio) / 2;
            mAllChildRect.top = 0;
            mAllChildRect.right = mAllChildRect.left + mViewRect.height() * mRatio;
            mAllChildRect.bottom = mViewRect.height();
        }
        int length = mTempletRectf.getLength();
        for (int i = 0; i < length; i++) {
            //获取子view的显示边界
            RectF boundRect = mTempletRectf.getRectf(i);
            RectF childRect = new RectF(mAllChildRect.left + boundRect.left * mAllChildRect.width(), mAllChildRect.top + boundRect.top * mAllChildRect.height(),
                    mAllChildRect.left + boundRect.right * mAllChildRect.width(), mAllChildRect.top + boundRect.bottom * mAllChildRect.height());
            BorderView borderView = new BorderView(getContext(), childRect);
            LayoutParams lp = new LayoutParams((int) (childRect.width() + 0.5), (int) (childRect.height() + 0.5));
            lp.topMargin = (int) (childRect.top + 0.5);
            lp.leftMargin = (int) (childRect.left + 0.5);
            EditMagazineChildRectfView magazineChildRectfView = new EditMagazineChildRectfView(getContext(), childRect, mAllChildRect);
            if (mSourceBitmap != null) {
                if (mSourceBitmap != null) {
//                    magazineChildRectfView.setSourceBitmap(mSourceBitmap, MagazineTempletConstant.totalTemplt[0][mItemPosition][0]);
                }
            }
            magazineChildRectfView.setTag(borderView);
            addView(magazineChildRectfView, lp);
        }
        if (mIsHasCoverView) {//有最上层透明遮盖层就要加上
            addView(new EditMagazineCoverView(getContext(), mCoverBitmap, mAllChildRect));
        }
    }

    //点击杂志列表,修改比例模板以及低图
    public void setRatioAnTempletAndBg(float ratio, int position, MagazineRectf rectf, Bitmap itemBitmap) {
//        mIsHasCoverView = MagazineTempletConstant.isHasMagazineCoverView_total[0][position];
        if (mIsHasCoverView) {
            int resId = 0;//MagazineTempletConstant.magazineCoverView_total[0][position];
            if (resId != 0) {
                mCoverBitmap = BitmapFactory.decodeResource(getResources(), resId);
            }
        }
        mBgBitmap = itemBitmap;
        mTempletRectf = rectf;
        mItemPosition = position;
        mRatio = ratio;
        mFlag = true;
        // 加到消息队列的最后,防界面闪烁
        post(new Runnable() {
            @Override
            public void run() {
                invalidate();
                invalidateCollage();
                mContext.dismissLoadingMagazineProgress();
            }
        });

    }

    public void setSourceBitmap(Bitmap bitmap) {//绘制原图
        mSourceBitmap = bitmap;
        int count = getChildCount();
        for (int i = count - 1; i >= 0; i--) {
            View view = getChildAt(i);
            if (!(view instanceof EditMagazineCoverView) && !(view instanceof BorderView)) {//除去最上层的透明层
                EditMagazineChildRectfView pathView = (EditMagazineChildRectfView) getChildAt(i);
                pathView.setSourceBitmap(mSourceBitmap);
            }
        }
    }

    /**
     * 合成成真正的图片
     * 遍历所有的子View  然后获取其Path 和源图片 绘制在画板上
     *
     * @return 返回合成后的图片
     */
    public Bitmap getCollageBitmap() {
        int width = getCollageBitmapWidth(mRatio);
        int height = (int) (width / mRatio + 0.5f);
        float scale = ImageHelper.checkCanvasAndTextureSizeHalf(width, height, 1);
        if (scale != 1) {
            width /= scale;
            height /= scale;
        }
        float currentWidth = mAllChildRect.width();
        float currentHeight = mAllChildRect.height();


        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Xfermode sXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
        Paint dSTPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        dSTPaint.setXfermode(sXfermode);

        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        bitmapPaint.setStyle(Paint.Style.FILL);
        Canvas canvas = new Canvas(bitmap);


        float scaleX = width / currentWidth;
        float scaleY = height / currentHeight;
        //这样处理是为了防止生成后的背景和原来的背景对不上, 整体缩放和平移
        canvas.scale(scaleX, scaleY);
        canvas.translate(-mAllChildRect.left, -mAllChildRect.top);
        canvas.drawBitmap(mBgBitmap, null, mAllChildRect, bitmapPaint);

        int count = getChildCount();

        for (int i = 0; i < count; i++) {//合成需要的图片
            int saveCount1 = canvas.saveLayer(0.0f, 0.0f, width, height,
                    null, Canvas.ALL_SAVE_FLAG);
            View view = getChildAt(i);
            if (!(view instanceof EditMagazineCoverView) && !(view instanceof BorderView)) {//除去最上层的透明层,和边界
                EditMagazineChildRectfView pathView = (EditMagazineChildRectfView) view;
                canvas.drawBitmap(pathView.getSrcRegineBitmap(), null, pathView.mDefaultRect, bitmapPaint);
                int saveCount2 = canvas.save();
//          需要把原来想对于父view的坐标转化成当前的view的坐标
                canvas.translate(pathView.mDefaultRect.left, pathView.mDefaultRect.top);
                //画图片
                canvas.drawBitmap(pathView.getSourceBitmap(), pathView.getDrawMatrix(), dSTPaint);
                canvas.restoreToCount(saveCount2);
            }

            //画最上层的透明层,保证只画一次
            if (mIsHasCoverView && view instanceof EditMagazineCoverView) {
                canvas.drawBitmap(mCoverBitmap, null, mAllChildRect, bitmapPaint);
            }
            canvas.restoreToCount(saveCount1);
        }

        return bitmap;
    }

    /**
     * 获取当前图片应有的宽高
     *
     * @param ratio
     * @return
     */
    public int getCollageBitmapWidth(float ratio) {
        float maxSize = ImageHelper.getCurrentMaxSize() / 4;
        return (int) Math.sqrt(maxSize * ratio);
    }


    @Override
    protected void onDraw(final Canvas canvas) {
        super.onDraw(canvas);
        if (mFlag) {
            // 画上背景
            canvas.drawBitmap(mBgBitmap, null, mAllChildRect, mBgPaint);
        }
    }

    private void dealSelectMove(float x, float y) {

        int count = getChildCount();
        for (int i = count - 1; i >= 0; i--) {
            View view = getChildAt(i);
            if (!(view instanceof EditMagazineCoverView) && !(view instanceof BorderView)) {//除去最上层的透明层
                EditMagazineChildRectfView pathView = (EditMagazineChildRectfView) view;
                RectF defaultRect = pathView.mDefaultRect;
                if (defaultRect.contains((int) x, (int) y)) {
                    mCurrentOperationView = pathView;
//                    mCurrentOperationView.setIsTouch(true);
                    mTouchMode = SELECTED_AND_MOVE;
                    return;
                }
            }
        }
        mTouchMode = SELECTED_NONE;
    }

    private void dealSelectUp(EditMagazineChildRectfView view, float x, float y) {
        if (view != null) {//用于处理缩小的过小的时候
            RectF rectF = view.mDefaultRect;
            float trueX = x - rectF.left;
            float trueY = y - rectF.top;
            view.onUp(trueX, trueY);
        }
    }

    /**
     * 处理点击
     */
    private void dealTapConfirm(float x, float y) {
        int count = getChildCount();
        mTouchMode = SELECTED_NONE;
        for (int i = count - 1; i >= 0; i--) {
            View view = getChildAt(i);
            if (!(view instanceof EditMagazineCoverView) && !(view instanceof BorderView)) {//除去最上层的透明层
                EditMagazineChildRectfView pathView = (EditMagazineChildRectfView) view;
                RectF defaultRect = pathView.mDefaultRect;
                if (defaultRect.contains((int) x, (int) y) && mTouchMode == SELECTED_NONE) {
                    mCurrentOperationView = pathView;
                    pathView.setIsTouch(false);
                } else {

                }
            }
        }
    }

    /**
     * 两个手指的时候执行
     */
    private void dealSelectScale(MotionEvent event) {
        float x1 = event.getX(0);
        float y1 = event.getY(0);

        float x2 = event.getX(1);
        float y2 = event.getY(1);

        float centerX = (x1 + x2) / 2;
        float centerY = (y1 + y2) / 2;

        int count = getChildCount();
        for (int i = count - 1; i >= 0; i--) {
            View view = getChildAt(i);
            if (!(view instanceof EditMagazineCoverView) && !(view instanceof BorderView)) {//除去最上层的透明层
                EditMagazineChildRectfView pathView = (EditMagazineChildRectfView) view;
                RectF region = pathView.mDefaultRect;
                if (region.contains((int) centerX, (int) centerY)) {
                    if (mCurrentOperationView == view) {
                        mCurrentOperationView.setIsTouch(true);
                        mTouchMode = SELECTED_AND_SCALE;
                        return;
                    } else {
                        if (mCurrentOperationView != null) {
                            mCurrentOperationView.setIsTouch(false);
                        }
                        int index = event.getActionIndex();
                        float x = event.getX(1 - index);
                        float y = event.getY(1 - index);
                        dealSelectUp(mCurrentOperationView, x, y);
                        mCurrentOperationView = pathView;
                        mCurrentOperationView.setIsTouch(true);
                        mTouchMode = SELECTED_AND_SCALE;
                        return;
                    }
                }
            }
        }
        mTouchMode = SELECTED_NONE;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int count = event.getPointerCount();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                if (count == 1) {
                    dealSelectMove(event.getX(), event.getY());
                } else {
                    mTouchMode = SELECTED_NONE;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                if (count == 2) {
                    dealSelectScale(event);
                } else {
                    mTouchMode = SELECTED_NONE;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                break;

        }
        mGestureRecognizer.onTouchEvent(event);
        return true;
    }

    @Override
    public boolean onSingleTapUp(float x, float y) {
        if (mTouchMode != SELECTED_AND_SCALE) {
            dealTapConfirm(x, y);
        }
        return true;
    }

    @Override
    public boolean onSingleTapComfirm(float x, float y) {
        return true;
    }

    @Override
    public boolean onDoubleTap(float x, float y) {
        return false;
    }

    @Override
    public boolean onScroll(float x, float y, float dx, float dy, float totalX, float totalY) {
        if (mCurrentOperationView == null) return true;
        if (mTouchMode == SELECTED_AND_MOVE) {
            mCurrentOperationView.onScroll(x, y, dx, dy, totalX, totalY);
        }
        mCurrentOperationView.setIsTouch(true);

        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return true;
    }

    @Override
    public boolean onScaleBegin(float focusX, float focusY) {
        return true;
    }

    @Override
    public boolean onScale(float focusX, float focusY, float scale) {
        if (mTouchMode == SELECTED_AND_SCALE && mCurrentOperationView != null) {
            RectF rectF = mCurrentOperationView.mDefaultRect;
            float trueFocusX = focusX - rectF.left;
            float trueFocusY = focusY - rectF.top;
            mCurrentOperationView.onScale(trueFocusX, trueFocusY, scale);
        }
        return true;
    }

    @Override
    public void onScaleEnd() {

    }

    @Override
    public boolean onRotaionBegin() {
        return false;
    }

    @Override
    public boolean onRotaion(float delta) {
        return false;
    }

    @Override
    public void onRotaionEnd() {

    }

    @Override
    public void onDown(float x, float y) {

    }

    @Override
    public void onUp(float x, float y) {
        dealSelectUp(mCurrentOperationView, x, y);
        if (mCurrentOperationView != null) {
            mCurrentOperationView.setIsTouch(false);
            mCurrentOperationView = null;
        }
        mTouchMode = SELECTED_NONE;
    }


    @Override
    public void onLongPress(float x, float y) {

    }

    //销毁
    public void destory() {

    }


    public void setMagazineDatas(ArrayList<MagazineBean> magazineDatas) {
        mMagazineDatas = magazineDatas;
    }
}